package com.hospicpc.demos.controller;


import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.commom.qiniuCloud;
import com.hospicpc.demos.entity.UserInfo;
import com.hospicpc.demos.service.Impl.UserInfoServiceImpl;
import com.hospicpc.demos.service.Impl.UserServiceImpl;
import com.hospicpc.demos.utils.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/upload")
public class UploadFileController {

    @Autowired
    public UserInfoServiceImpl userInfoService;

    @PostMapping("/updateAvatarUrl")
    public Result updateAvatarUrl(@RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest){
        //获取用户id
        String userId = httpServletRequest.getParameter("userId");
        if(userId == null) {
            return Result.error("用户id为空");
        }
        if(file == null) {
            return Result.error("图片为空");
        }
        String key;
        //上传图片到七牛云
        try {
            key = UploadFileUtils.upload(file, httpServletRequest.getParameter("userId"));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }

        //保存到数据库
        userInfoService.lambdaUpdate().set(UserInfo::getAvatarUrl, qiniuCloud.DOMAIN_NAME + key)
                .eq(UserInfo::getUserId, userId)
                .update();

        return Result.success(qiniuCloud.DOMAIN_NAME + key);

    }
}
